package br.com.mtg.movethegarbage.framework;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;

public class Music implements OnCompletionListener
{
	MediaPlayer player;
	boolean isPrepared;

	public Music(AssetFileDescriptor assetFileDescriptor)
	{
		player = new MediaPlayer();
		try
		{
			player.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void dispose()
	{
		if (isPlaying())
			stop();
		player.release();
	}

	public void play()
	{
		if (isPlaying())
			return;
		if (!isPrepared)
			try
			{
				player.prepare();
			}
			catch (Exception e)
			{
				Log.e("Music", "Could not prepare music for play");
			}
		player.start();
	}

	public void pause()
	{
		if (isPlaying())
			player.pause();
	}

	public void stop()
	{
		if (isPlaying())
			player.stop();
		isPrepared = false;
	}

	public boolean isPlaying()
	{
		return player.isPlaying();
	}

	public boolean isLooping()
	{
		return player.isLooping();
	}

	public boolean isStopped()
	{
		return !player.isPlaying();
	}

	public void setLooping(boolean looping)
	{
		player.setLooping(looping);
	}

	public void setVolume(float volume)
	{
		player.setVolume(volume, volume);
	}

	public void onCompletion(MediaPlayer mp)
	{
		isPrepared = false;
	}

}
